Skip to main content

Power of Two

LeetCode 231 | Difficulty: Easy​

Easy

Problem Description​

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two, if there exists an integer x such that n == 2^x.

Example 1:

Input: n = 1
Output: true
Explanation: 2^0 = 1

Example 2:

Input: n = 16
Output: true
Explanation: 2^4 = 16

Example 3:

Input: n = 3
Output: false

Constraints:

- `-2^31 <= n <= 2^31 - 1`

Follow up: Could you solve it without loops/recursion?

Topics: Math, Bit Manipulation, Recursion


Approach​

Bit Manipulation​

Operate directly on binary representations. Key operations: AND (&), OR (|), XOR (^), NOT (~), shifts (<<, >>). XOR is especially useful: a ^ a = 0, a ^ 0 = a.

When to use

Finding unique elements, power of 2 checks, subset generation, toggling flags.

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.


Solutions​

Solution 1: C# (Best: 44 ms)​

MetricValue
Runtime44 ms
MemoryN/A
Date2018-04-12
Solution
public class Solution {
public bool IsPowerOfTwo(int n) {
if(n<=0) return false;
var x = n & n-1;
return x==0;
}
}

Complexity Analysis​

ApproachTimeSpace
Bit Manipulation$O(n) or O(1)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.